const dgram = require('dgram');
const WebSocket = require('ws');
const server = dgram.createSocket('udp4');

// 创建WebSocket服务器
const wss = new WebSocket.Server({ port: 8080 });

// 存储所有连接的WebSocket客户端
const clients = new Set();

// WebSocket连接处理
wss.on('connection', (ws) => {
    clients.add(ws);
    console.log('新的WebSocket客户端已连接');

    ws.on('close', () => {
        clients.delete(ws);
        console.log('WebSocket客户端已断开连接');
    });
});

// UDP服务器监听
server.on('error', (err) => {
    console.log(`UDP服务器错误:\n${err.stack}`);
    server.close();
});

server.on('message', (msg, rinfo) => {
    const value = msg.toString();
    console.log(`收到UDP消息: ${value} 来自 ${rinfo.address}:${rinfo.port}`);
    
    // 将UDP消息转发给所有WebSocket客户端
    clients.forEach(client => {
        if (client.readyState === WebSocket.OPEN) {
            client.send(value);
        }
    });
});

server.on('listening', () => {
    const address = server.address();
    console.log(`UDP服务器监听 ${address.address}:${address.port}`);
});

// 监听UDP端口
server.bind(41234); 